const crypto = require('crypto');
const {infoLogger, errorLogger} = require('../../config').logger;
let ErrorUtils = require('../error/ErrorUtils');
module.exports = class WXBizDataCrypt {
    constructor(appId, sessionKey) {
        this.appId = appId;
        this.sessionKey = sessionKey;
    }
    decryptData(_encryptedData, _iv) {
        // base64 decode
        //这里new Buffer 和Buffer.from
        const sessionKey = new Buffer(this.sessionKey, 'base64'),
            encryptedData = new Buffer(_encryptedData, 'base64'),
            iv = new Buffer(_iv, 'base64');
        try {
            // 解密
            let decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
            // 设置自动 padding 为 true，删除填充补位
            decipher.setAutoPadding(true);
            let decoded = decipher.update(encryptedData, 'binary', 'utf8');
            decoded += decipher.final('utf8');
            //console.log(decoded);
            decoded = JSON.parse(decoded);

            if (decoded.watermark.appid !== this.appId) {
                ErrorUtils.throwApiError(ErrorUtils.APPID_NOT_MATCH);
            }
            return decoded;
        } catch (err) {
            errorLogger.error(err);
            ErrorUtils.throwApiError(ErrorUtils.DECODE_PASSWORD_ERROR);
        }
    }
};
